import { defineStore } from 'pinia'
import type { RegisterData } from '@/types/auth/RegisterData'
import type { ApiResponse } from '@/api/types'
import { sendVerificationCodeApi,validateCodeApi,registerApi } from '@/api/auth/register'
import { useUserStore } from '@/stores/auth/user'
export const useRegisterStore = defineStore('register', {
  state: () => ({
    user:{
      id: 0,
      email: '',
      username: '',
      password: ''
    },
    token: '',
    verificationToken: ''
  }),
  actions: {
    setVerificationToken(token: string) {
      this.verificationToken = token
    },
    clearVerificationToken() {
      this.verificationToken = ''
    },
    setEmail(email: string) {
      if (this.user) {
        this.user.email = email
      }
    },
    setUsername(username: string) {
      if (this.user) {
        this.user.username = username
      }
    },
    setPassword(password: string) {
      if (this.user) {
        this.user.password = password
      }
    },
    setToken(token: string) {
      this.token = token
    },
    clear() {
      this.user = {
        id: 0,
        email: '',
        username: '',
        password: ''
      }
      this.token = ''
    },
    async sendVerificationCode(email: string, purpose: string) {
      // 
      const res : ApiResponse<any> = await sendVerificationCodeApi({ email, purpose })
      // console.log('发送验证码响应:', res)
      // 若后端返回 verificationToken，保存到 store（仅内存）
      const token = res?.data?.verificationToken
      if (token) this.setVerificationToken(token)
      else console.warn('未收到 verificationToken')
      if (res.code === 0 || res.code === 200) {
        console.log('验证码发送成功')
        return true
      } else {
        throw new Error(res.message || '发送验证码失败')
      }
    },
    async validateCode(email: string, code: string, purpose: string) {
      // console.log('验证验证码:', email, code, purpose)
      const res: ApiResponse<null> = await validateCodeApi({ email, code, purpose, verificationToken: this.verificationToken })
      if(res.code === 0 || res.code === 200) {
        console.log('验证码验证成功')
        return true
      }
      else{
        throw new Error(res.message || '验证码验证失败')
      }
    },
    async register(username: string, password: string) {
      const email = this.user?.email || ''
      const res: ApiResponse<null> = await registerApi({ username, email, password })
      console.log('注册响应:', res)

      if (res.code === 0 || res.code === 200) {
        console.log('注册成功')
        const accessToken = res.accessToken || ''
        this.setToken(accessToken)

        if (accessToken) {
          console.log("yes")
          const userStore = useUserStore()
          userStore.setToken(accessToken)
          await userStore.fetchUserInfo()
        }
        return true
      } else {
        throw new Error(res.message || '注册失败')
      }
    }
  }
})
